package com.jp.knowledge.my.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.widget.TextView;

import com.jp.knowledge.R;

/**
 * 圆角矩形
 *
 * @author gzejia 978862664@qq.com
 */
public class RoundRectView extends TextView {

    // 颜色
    private int mPaintColor;
    // 圆角弧度
    private int mRadiusSize;
    // 背景填充
    private boolean mIsFill;
    // 矩形宽度
    private int mWidth;
    // 矩形高度
    private int mHeight;
    // 全局
    private Context mContext;

    public RoundRectView(Context context) {
        super(context);
        this.mContext = context;
    }

    public RoundRectView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.roundRect_style);
        this.mPaintColor = typedArray.getColor(R.styleable.roundRect_style_paint_color, Color.RED);
        this.mRadiusSize = typedArray.getInt(R.styleable.roundRect_style_radian_size, 8);
        this.mIsFill = typedArray.getBoolean(R.styleable.roundRect_style_fill, true);
    }

    public RoundRectView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
    }


    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        this.mWidth = getWidth();
        this.mHeight = getHeight();
    }

    /**
     * @param paintColor 设置颜色 可默认
     */
    public void setPaintColor(int paintColor) {
        this.mPaintColor = paintColor;
        invalidate();
    }

    /**
     * @param radiusSize 设置圆角大小 可默认
     */
    public void setRadiusSize(int radiusSize) {
        this.mRadiusSize = radiusSize;
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {

        Paint paint = new Paint();
        paint.setStyle(mIsFill ? Paint.Style.FILL : Paint.Style.STROKE);
        paint.setColor(mPaintColor);
        paint.setAntiAlias(true);
        paint.setStrokeWidth(3.0f);

        RectF rectF = new RectF(0, 0, mWidth, mHeight);
        int mRadiusSizePx = dip2px(mContext, mRadiusSize);
        canvas.drawRoundRect(rectF, mRadiusSizePx, mRadiusSizePx, paint);

        super.onDraw(canvas);
    }

    /**
     * @param context Context
     * @param dpValue （DisplayMetrics类中属性scaledDensity）
     * @return 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}

